<script>
import nullCont from '@/views/components/nullCont/nullCont'
export default {
    name: 'proTable',
    props: {
        tableConfig: {
            type: Object
        },
        pageConfig: {
            type: Object
        },
        checkedboxText: {
            type: String
        },
        showGrid: {
            type: Boolean,
            default: false
        }
    },
    components: {
        nullCont
    },
    render () {
        this.tabName = this.$route.query.type || 'own'
        const styles = this.tableConfig.table.style || {}
        return (
            <div class="pro-table" style={{ ...styles }}>
                {<el-table
                    ref="proTable"
                    border
                    stripe
                    tooltip-effect="dark"
                    style="margin:15px 0; overflow: hidden;"
                    header-cell-class-name="pro-table-header header-content"
                    row-key={this.setRowKey}
                    style={{ ...styles, height: !this.tableConfig.dialog && this.tableHeight }}
                    element-loading-text="拼命加载中"
                    {...{ props: this.tableConfig.table, on: this.tableConfig['tableEvents'], directives: this.directives }}
                    on-select-all ={this.rowSelectAllChange}
                    on-select ={this.rowSelectChange}
                    height={this.tableHeight}
                >
                    {
                        this.tableConfig.columns.map((item, columnIndex) => {
                            if (item.hide) return null
                            return item.slot &&
                            (!item.hasOwnProperty('permission') || (item.hasOwnProperty('permission') && this.$permission(item.permission))) &&
                            (!item.hasOwnProperty('tabType') || (item.hasOwnProperty('tabType') && item.tabType.includes(this.tabName)))
                                ? (this.$slots[item.slot] || this.$parent.$slots[item.slot])
                                : ((!item.hasOwnProperty('permission') || (item.hasOwnProperty('permission') && this.$permission(item.permission))) &&
                                (!item.hasOwnProperty('tabType') || (item.hasOwnProperty('tabType') && item.tabType.includes(this.tabName)))
                                    ? <el-table-column align="center" { ...{ props: item } } key={columnIndex}></el-table-column> : null)
                        })
                    }
                    {
                        this.tableConfig.table.data.length === 0 ? (
                            <nullCont
                                style={{ padding: '150px 0', ...this.tableConfig.emptyStyle }}
                                text={this.tableConfig.noDataText}
                                slot="empty"
                            ></nullCont>
                        ) : null
                    }
                </el-table>}
                {this.pageConfig ? <div class="table-bottom clearfix">
                    {this.tableConfig.table['selection-key']
                        ? <el-checkbox
                            class="check-all fl"
                            disabled={!this.tableConfig.table.data.length}
                            value={this.tableConfig.checkAll} on-change={value => { this.handleCheckAllChange(value) }}
                        >{this.checkedboxText || '选择当前搜索条件下全部数据'}</el-checkbox> : null
                    }
                    {
                        this.tableConfig.table.data.length > 0 && this.pageConfig ? (
                            <el-pagination
                                // 设置默认值
                                background
                                page-sizes={[10, 20, 50, 100, 200]}
                                page-size={20}
                                pager-count={5}
                                layout='total, sizes, prev, pager, next, jumper'
                                class="pagination fr"
                                { ...{ props: this.pageConfig.attr, on: this.pageConfig.event } }>
                            </el-pagination>
                        ) : null
                    }

                </div> : null}
            </div>
        )
    },
    computed: {
        directives () {
            return [{ name: 'loading', value: this.tableConfig.loading }]
        }
    },
    watch: {
        'tableConfig.table.data': {
            handler () {
                this.toggleAllSelection()
            },
            immediate: true
        },
        isGrid () {
            this.tableConfig.checkAll = false
            this.$refs.proTable && this.$refs.proTable.clearSelection()
            this.checkedItems = []
            setTimeout(() => {
                this.setTableHeight()
            }, 50)
            this.tableConfig.table.unSelectedRow = []
        }
    },
    data () {
        return {
            identifyKey: '',
            checkAll: false,
            multipleSelection: [],
            tableHeight: 400,
            tabName: 'own',
            statusType: this.$parent.statusType,
            checkedItems: [],
            isIndeterminate: false
        }
    },
    methods: {
        resetTable () {
            this.tableConfig.checkAll = false
            this.tableConfig.loading = true
            this.checkedItems = []
            this.$refs.proTable && this.$refs.proTable.clearSort()
            if (this.pageConfig) {
                this.pageConfig.attr['current-page'] = 1
                this.pageConfig.attr['page-size'] = 20
            }
            this.tableConfig.table.unSelectedRow = []
            this.tableConfig.table.selectedRow = []
            this.toggleAllSelection()
        },
        // 设置表格高度自适应屏幕大小
        setTableHeight () {
            let h = document.documentElement.clientHeight || document.body.clientHeight
            let proTable = this.$refs.proTable
            let multipleGridTable = this.$refs.multipleGridTable
            let offset = this.tableConfig.table.offset
            if (proTable) {
                let offsetTop = proTable.$el.offsetTop > 100 ? proTable.$el.offsetTop : 185
                this.tableHeight = h - offsetTop - 200 + 'px'
                if (offset) {
                    this.tableHeight = h - ((offset.top || 0) + (offset.bottom || 0)) + 'px'
                }
                proTable.doLayout()
            } else if (multipleGridTable) {
                this.tableHeight = h - multipleGridTable.offsetTop - 200
            }
        },
        // 远程搜索分类
        async onFilterCategory (queryString, formItem) {
            let res = await this.$api.category.searchCategory({ categoryName: queryString })
            if (res && res.success) {
                if (!res.result || res.result === null) {
                    return
                }
                res.result.map(el => {
                    el.categoryName = el.categoryName.split('>').join('/')
                })
                var filterCateList = res.result
                var results = queryString ? filterCateList.filter(_ => _.categoryName.includes(queryString)) : filterCateList
                // 调用 callback 返回建议列表的数据
                let hasQueryStr = results.length
                hasQueryStr && (formItem.innerEl.options = results)
                // if (!hasQueryStr || !queryString) {
                //     formItem.innerEl.options = this.filterData.categoryList
                // }
            }
        },
        // 网格列表全选
        handleCheckAllChange (val) {
            this.checkedItems = val ? this.tableConfig.table.data.map(el => {
                let id = el[this.tableConfig.table['selection-key']]
                return id
            }) : []
            this.isIndeterminate = false
            this.tableConfig.checkAll = val
            this.tableConfig.table.selectedRow = this.checkedItems.filter(el => el)
            this.toggleAllSelection(val)
        },
        // 网格列表多选
        handlecheckedItemsChange (value) {
            if (this.statusType === 'offline') {
                let selectArr = value
                this.selectArrHas = this.selectArrHasFn(selectArr)
            }
            console.log(value, 'handlecheckedItemsChange')
            let checkedCount = value.length
            this.isIndeterminate = checkedCount > 0 && checkedCount < this.tableConfig.table.data.length
            this.checkedItems = value
            this.$emit('selection-change', value)
            this.tableConfig.checkAll = false
        },
        // 选择所有过滤的内容
        toggleAllSelection (val) {
            if (this.$refs.proTable) {
                if (this.tableConfig.checkAll || val) {
                    // 设置选中，table组件需要使用ref="table"
                    this.tableConfig.table.data.forEach(el => {
                        /**
                         * 表格全选时，如果需要使用反选功能放开此处
                         */
                        // let unSelectedRow = this.tableConfig.table.unSelectedRow
                        // let id = el[this.tableConfig.table['selection-key']] || el.id
                        // if (unSelectedRow.length && unSelectedRow.includes(id)) {
                        //     this.$refs.proTable.toggleRowSelection(el, false)
                        // } else {
                        //     this.$refs.proTable.toggleRowSelection(el, true)
                        // }
                        this.$refs.proTable.toggleRowSelection(el, true)
                    })
                } else {
                    if (this.checkedItems && !this.checkedItems.length && !this.tableConfig.checkAll) {
                        this.$refs.proTable && this.$refs.proTable.clearSelection()
                    }
                    this.isIndeterminate = false
                }
            } else if (this.$refs.multipleGridTable) {
                if (this.tableConfig.checkAll || val) {
                    this.checkedItems = [...this.checkedItems, ...this.tableConfig.table.data.map(el => {
                        let id = el[this.tableConfig.table['selection-key']] || el.id
                        return id
                    })]
                } else {
                    if (this.checkedItems && !this.checkedItems.length && !this.tableConfig.checkAll) {
                        this.checkedItems = []
                    }
                    this.isIndeterminate = false
                }
            }
        },
        // 翻页回选
        setRowKey (data) {
            return data.id
        },
        turnToPage (route) {
            let { name, params, query, meta } = {}
            if (typeof route === 'string') name = route
            else {
                name = route.name
                params = route.params
                query = route.query
                meta = route.meta
            }
            if (name.indexOf('isTurnByHref_') > -1) {
                let { href } = this.$router.resolve({ name: name.split('_')[1], query: query })
                window.open(href, '_blank')
                return
            }
            this.$router.push({
                name,
                params,
                query,
                meta
            })
        },
        handleSelectionChange (val) {
            this.checkedItems = val.map(el => {
                let id = el[this.tableConfig.table['selection-key']] || el.id
                return id
            })
            this.tableConfig.table.selectedRow = this.checkedItems
        },
        rowSelectAllChange (selection) {
            // let unSelectedRow = this.tableConfig.table.unSelectedRow
            // let data = this.tableConfig.table.data
            // unSelectedRow = [...unSelectedRow, ...data.map(el => {
            //     let id = el[this.tableConfig.table['selection-key']] || el.id
            //     return id
            // })]
            // selection.map(el => {
            //     let id = el[this.tableConfig.table['selection-key']] || el.id
            //     unSelectedRow = unSelectedRow.filter(el => el !== id)
            // })
            // this.tableConfig.table.unSelectedRow = unSelectedRow
            // console.log(selection, unSelectedRow)
        },
        rowSelectChange (selection, row) {
            // let unSelectedRow = this.tableConfig.table.unSelectedRow
            // let id = row[this.tableConfig.table['selection-key']] || row.id
            // if (this.checkedItems.includes(id)) {
            //     unSelectedRow = unSelectedRow.filter(el => el !== id)
            // } else {
            //     unSelectedRow = [...unSelectedRow, id]
            // }
            // this.tableConfig.table.unSelectedRow = unSelectedRow
            // console.log(unSelectedRow, row)
            this.tableConfig.table.selectedRow = this.checkedItems.filter(el => el)
        },
        // 表格排序
        handleSort (filters, props) {
            let sortValue = ''
            let propsObj = {}
            if (props) {
                propsObj = props
            }
            console.log(filters.prop, 'filters.prop')
            for (let key in propsObj) {
                if (key.indexOf(filters.prop) > -1) {
                    console.log(key, 'key')
                    sortValue = propsObj[key]
                    if (filters.order.indexOf('desc') > -1) {
                        sortValue += '.desc'
                    } else {
                        sortValue += '.asc'
                    }
                }
            }
            return sortValue
        }
    },
    created () {
        let tableMethods = this.tableConfig.tableMethods || (this.$parent.tableConfig && this.$parent.tableConfig.tableMethods) || {}
        for (let item in tableMethods) {
            tableMethods[item] = tableMethods[item].bind(this)
        }
    },
    mounted () {
        let vm = this
        this.$refs.proTable.$on('selection-change', function (val) {
            vm.multipleSelection = val
            vm.handleSelectionChange(val)
        })
        this.$nextTick(function () {
            this.isUpdate = true
            this.tableHeight = this.tableConfig.table.height + 'px'
            this.setTableHeight()
        })
        window.addEventListener('resize', () => {
            this.setTableHeight()
        })
    }
}
</script>
<style lang="less" scoped>
.pro-table {
    background-color: @white;
    padding: 30px 0;
    /deep/ .el-table__header-wrapper {
        border-bottom: 0;
    }
    /deep/ .el-table--border th:first-child .cell,
    /deep/ .el-table--border td:first-child .cell {
        padding: 0;
    }
    & /deep/ .el-table__fixed::before,
    & /deep/ .el-table__fixed-right::before {
        display: none !important;
    }
    .title {
        position: relative;
        margin-bottom: 16px;
        &::before {
            content: "";
            width: 3px;
            height: 12px;
            background-color: @primary;
            position: absolute;
            top: 2px;
        }
        h3 {
            font-size: 14px;
            color: #333;
            margin-left: 14px;
        }
    }
    /deep/ .btns {
        display: flex;
        justify-content: space-around;
    }
    .table-bottom {
        margin-top: 20px;
        .check-all {
            left: 15px;
        }
    }
    /deep/ td {
        color: @c-666;
    }
    /deep/ th {
        background-color: @f8;
    }
    /deep/ td .cell {
        color: inherit;
        max-height: fit-content;
    }
}
</style>
